<template>
  <div class="form">
    <van-field v-model="tel" type="tel" placeholder="请输入手机号" clearable/>
    <div class="my-button">
      <van-button :disabled="flag" color="#ff6666" @click="checkTel" block round>下一步</van-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, Dialog } from 'vant'
import { doCheckPhone } from '@/api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(Dialog)
export default {
  data () {
    return {
      tel: ''
    }
  },
  computed: {
    flag () {
      if (/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(this.tel)) {
        return false
      } else {
        return true
      }
    }
  },
  methods: {
    checkTel () {
      doCheckPhone({ tel: this.tel }).then(res => {
        if (res.data.code === '10005') {
          // 手机号码被注册，提醒用户是不是直接登录
          Dialog.confirm({
            message: '该手机号已被注册，是否直接登录',
            confirmButtonText: '直接登录',
            confirmButtonColor: '#ff6666',
            cancelButtonText: '取消',
            cancelButtonColor: '#999'
          })
            .then(() => {
              // on confirm
              // this.$router.push('/login') // ? replace
              this.$router.back()
            })
            .catch(() => {
              // on cancel
            })
        } else {
          // 手机号码没有被注册，提醒用户即将发送短信给用户，确定以后跳转至发送短信验证码页面
          Dialog.confirm({
            message: '我们将发送短信验证码至您的手机号',
            confirmButtonText: '确定',
            confirmButtonColor: '#ff6666',
            cancelButtonText: '取消',
            cancelButtonColor: '#999'
          })
            .then(() => {
              // on confirm
              // 记得保存手机号吗到本地，因为在另一个页面发送验证码时要知道发送给谁
              localStorage.setItem('tel', this.tel)
              this.$router.push('/register/step2')
            })
            .catch(() => {
              // on cancel
            })
        }
      })
    }
  }
}
</script>
<style lang="stylus">
.form
  .my-button
    margin-top 30px
</style>
